package org.shoukaiseki.web.config.exec;

import com.alibaba.fastjson.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.shoukaiseki.web.config.SeleniumComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * org.shoukaiseki.web.config.exec.SeleniumActuator <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  2019-01-20 18:07:45<br>
 * ブログ http://shoukaiseki.blog.163.com/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/
public class SeleniumActuator {

    static final Logger logger=LoggerFactory.getLogger(SeleniumActuator.class);

   private WebDriver driver ;

   static String url="https://ccare.crm.huawei.com";

   private static String searchJs;

   WebElement imeisnEle;

    public static String getSearchJs() {
        return searchJs;
    }

    public static void setSearchJs(String searchJs) {
        if(SeleniumActuator.searchJs!=null){
            SeleniumActuator.searchJs = searchJs;
        }
    }

    public void login(String username,String password){
        if(driver!=null){
            try {
                driver.close();
            }catch (Throwable t){
                logger.warn("",t);
            }
        }
        logger.debug("登录......");
        driver = new FirefoxDriver();
        driver.manage().timeouts().setScriptTimeout(99999, TimeUnit.HOURS);
        driver.manage().timeouts().implicitlyWait(99999, TimeUnit.HOURS);
        driver.manage().timeouts().pageLoadTimeout(99999, TimeUnit.HOURS);
        driver.get(url);

        WebElement elemUsername = driver.findElement(By.id("uid")); //获取用户名框
        WebElement elemPassword = driver.findElement(By.id("password")); //获取密码框
        //登录按钮
        By loginButton = By.cssSelector("input[class='login_submit_pwd']");
        //也可以用这个
//       loginButton=By.className("login_submit_pwd");
        WebElement btn = driver.findElement(loginButton);    //获取点击登陆按钮。

        elemUsername.sendKeys(username);
        elemPassword.sendKeys(password);
        // 点击行为；
        btn.submit();

        logger.debug("成功登录");

        //查询点击元素
        By flyoutAnchorArrow = By.className("flyoutAnchorArrow");

        logger.debug("-------------CurrentUrl="+driver.getCurrentUrl());

        WebDriverWait wait = new WebDriverWait(driver, 60);
        wait.until(ExpectedConditions.presenceOfElementLocated(flyoutAnchorArrow));

        //点击查询
        WebElement searchs=driver.findElement(flyoutAnchorArrow);
        searchs.click();


        //权益查询元素

        By rightsrightSearchText = By.linkText("权益查询");

//        By rightsrightSearch = By.className("ms-crm-CommandBar-Menu");
//        rightsrightSearch =By.cssSelector("a[class='ms-crm-Menu-Label']");
        wait.until(ExpectedConditions.presenceOfElementLocated(rightsrightSearchText));
        //点击 权益查询
        WebElement rightsrightSearchEle=driver.findElement(rightsrightSearchText);
        logger.debug(rightsrightSearchEle.getTagName());
//        System.out.println(rightsrightSearchEle.getLocation());
//        System.out.println(rightsrightSearchEle.getRect());
//        System.out.println(rightsrightSearchEle.getSize());
//        System.out.println(rightsrightSearchEle.getText());

        //权益查询点击
        rightsrightSearchEle.click();

        //SN输入框id  imeisn
        //查询按钮id  Select


        Set<String> childids = driver.getWindowHandles();

        for(String s:childids){
            if(driver.switchTo().window(s).getTitle().contains("rightsrightsearch")){
                driver.switchTo().window(s);
                String titleChild = driver.getTitle();
                logger.debug("-----titleChild="+titleChild);
//                logger.debug("name:"+titleChild);
                break;
            }
        }

        WebDriver rightsrightsearch = driver;

        By imeisn = By.id("imeisn");
        By selectButton = By.id("Select");
//        WebDriverWait wait2 = new WebDriverWait(driver, 60);
//        wait2.until(ExpectedConditions.presenceOfElementLocated(imeisn));
        imeisnEle = rightsrightsearch.findElement(imeisn);
//        WebElement selectButtonEle = rightsrightsearch.findElement(selectButton);
//        imeisnEle.sendKeys("868802049323827");
//        selectButtonEle.click();

//        Thread.sleep(30000L);

    }

    public Object search(String imeisn){
        imeisnEle = driver.findElement(By.id("imeisn"));
        imeisnEle.clear();
        imeisnEle.sendKeys(imeisn);

        StringBuilder js=new StringBuilder("imeisn = '"+imeisn+"';\n").append(getSearchJs());

        WebDriverWait executeJSwait = new WebDriverWait(driver, 10);
        ((RemoteWebDriver) driver).executeScript(js.toString());
        Object asus = executeJSwait.until(new Function<WebDriver, Object>() {

            @Override
            public Object apply( @Nullable WebDriver driver) {
                return ((RemoteWebDriver) driver).executeScript("return window.asus;");
            }
        });

        if(logger.isDebugEnabled()){
            logger.debug("asus={}", JSONObject.toJSONString(asus));
        }
        return asus;
    }

    public Object test2(){
        return driver;
    }

    public Object test(String js){
        WebDriverWait executeJSwait = new WebDriverWait(driver, 30);
        ((RemoteWebDriver) driver).executeScript(js);
        Object asus = executeJSwait.until(new Function<WebDriver, Object>() {

            @Override
            public Object apply( @Nullable WebDriver driver) {
                return ((RemoteWebDriver) driver).executeScript("return window.asus;");
            }
        });

        if(logger.isDebugEnabled()){
            logger.debug("asus={}", JSONObject.toJSONString(asus));
        }
        return asus;
    }
}
